<?php

namespace app\api\controller\User;

use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
    }

    public function login()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code','');

            if(!$code)
            {
                $this->error('临时授权失败');
                exit;
            }

            $result = $this->code2Session($code);

            $openid = isset($result['openid']) ? $result['openid'] : '';

            if(!$openid)
            {
                $this->error('获取登录凭证失败');
                exit;
            }

            $User = $this->UserModel->where(['openid' => $openid])->find();

            if($User === FALSE)
            {
                $this->error('请先绑定账号','user/base/bind');
                exit;
            }else{
                $data = [
                    'id'=>$User['id'],
                    'openid'=>$User['openid'],
                    'email'=>$User['email'],
                    'nickname'=>$User['nickname'],
                    'avatar'=>$User['avatar_cdn'],
                    'sex'=>$User['sex'],
                    'sex_text'=>$User['sex_text'],
                    'province'=>$User['province'],
                    'city'=>$User['city'],
                    'district'=>$User['district'],
                    'createtime'=>$User['createtime'],
                    'content'=>$User['content'],
                    'point'=>$User['point'],
                    'vip'=>$User['vip'],
                    'auth'=>$User['auth'],
                    'cover'=>$User['cover_cdn'],
                    'region'=>explode('-', $User['region']),
                    'region_text'=>$User['region']
                ];

                $this->success('登录成功',null,$data);
                exit;
            }
        }
    }
    public function bind()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code','');

            if(!$code)
            {
                $this->error('获取临时登录凭证失败');
                exit;
            }

            // 换取openid
            $result = $this->code2Session($code);

            $openid = isset($result['openid']) ? $result['openid'] : '';

            if(!$openid)
            {
                $this->error('获取登录凭证失败');
                exit;
            }

            $user = $this->UserModel->where(['openid' => $openid])->find();

            if($user)
            {
                $this->success('账号已绑定，无须重复绑定');
                exit;
            }

            $email = $this->request->param('email','');

            $password = $this->request->param('password','');

            if(!$email)
            {
                $this->error('邮箱不能为空');
                exit;
            }

            if(!$password)
            {
                $this->error('密码不能为空');
                exit;
            }

            $check = $this->UserModel->where('email',$email)->find();

            if($check)
            {
                if($check['openid'])
                {
                    $this->success('账号已绑定，无须重复绑定');
                    exit;
                }

                $password = md5($password . $check['salt']);

                if($password != $check['password'])
                {
                    $this->error('密码错误');
                    exit;
                }

                $data = [
                    'id' => $check['id'],
                    'openid' => $openid,
                ];

                $res = $this->UserModel->validate('common/User/User.check')->isUpdate(true)->save($data);
                
                if($res === FALSE)
                {
                    $this->error($this->UserModel->getError());
                    exit;
                }else{

                    $User = $this->UserModel->where(['email' => $email, 'password' => $password])->find();

                    $data = [
                        'id'=>$User['id'],
                        'openid'=>$User['openid'],
                        'email'=>$User['email'],
                        'nickname'=>$User['nickname'],
                        'avatar'=>$User['avatar_cdn'],
                        'sex'=>$User['sex'],
                        'sex_text'=>$User['sex_text'],
                        'province'=>$User['province'],
                        'city'=>$User['city'],
                        'district'=>$User['district'],
                        'createtime'=>$User['createtime'],
                        'content'=>$User['content'],
                        'point'=>$User['point'],
                        'vip'=>$User['vip'],
                        'auth'=>$User['auth'],
                        'cover'=>$User['cover_cdn'],
                        'region'=>explode('-', $User['region']),
                        'region_text'=>$User['region']
                    ];
    
                    $this->success('绑定成功',null,$data);
                    exit;
                }
            }else{
                $salt = build_ranstr();

                $password = md5($password.$salt);

                $data = [
                    'email' => $email,
                    'password' => $password,
                    'salt' => $salt,
                    'openid' => $openid
                ];

                $res = $this->UserModel->validate('common/User/User.save')->save($data);

                if($res === FALSE)
                {
                    $this->error($this->UserModel->getError());
                    exit;
                }else{
                    $User = $this->UserModel->where(['email' => $email, 'password' => $password])->find();

                    $data = [
                        'id'=>$User['id'],
                        'openid'=>$User['openid'],
                        'email'=>$User['email'],
                        'nickname'=>$User['nickname'],
                        'avatar'=>$User['avatar_cdn'],
                        'sex'=>$User['sex'],
                        'sex_text'=>$User['sex_text'],
                        'province'=>$User['province'],
                        'city'=>$User['city'],
                        'district'=>$User['district'],
                        'createtime'=>$User['createtime'],
                        'content'=>$User['content'],
                        'point'=>$User['point'],
                        'vip'=>$User['vip'],
                        'auth'=>$User['auth'],
                        'cover'=>$User['cover_cdn'],
                        'region'=>explode('-', $User['region']),
                        'region_text'=>$User['region']
                    ];
    
                    $this->success('绑定成功',null,$data);
                    exit;
                }
            }

        }
    }

     // 修改资料
     public function profile()
     {
         if($this->request->isPost())
         {
             $userid = $this->request->param('userid',0);
             $nickname = $this->request->param('nickname','');
             $sex = $this->request->param('sex',0);
             $code = $this->request->param('code',0);
             $content = $this->request->param('content','');
 
             $User = $this->UserModel->find($userid);
 
             if(!$User)
             {
                 $this->error('用户不存在');
                 exit;
             }
 
             $data = [
                 'id' => $userid,
                 'nickname' => $nickname,
                 'sex' => $sex,
                 'content' => $content
             ];
 
             if($code)
             {
                 $parentpath = model('Region')->where(['code'=>$code])->value('parentpath');
 
                 if(!$parentpath)
                 {
                     $this->error('所选地区不存在');
                     exit;
                 }
 
                 [$province,$city,$district] = explode(',',$parentpath);
 
                 if($province)
                 {
                     $data['province'] = $province;
                 }
 
                 if($city)
                 {
                     $data['city'] = $city;
                 }
 
                 if($district)
                 {
                     $data['district'] = $district;
                 }
             }
 
             if($_FILES && $_FILES['cover']['size'] > 0)
             {
                 $cover = upload('cover');
 
                 if($cover === FALSE)
                 {
                     $this->error('上传失败');
                     exit;
                 }
 
                 $data['cover'] = $cover;
             }
 
             $result = $this->UserModel->isUpdate(true)->save($data);
 
             if($result === FALSE)
             {
                 @is_file(ROOT_PATH . 'public' . DS . $cover) && @unlink(ROOT_PATH . 'public' . DS . $cover);
                 $this->error('更新个人资料失败');
                 exit;
             }else{
                 
                 if($_FILES && $_FILES['cover']['size'] > 0)
                 {
                     @is_file(ROOT_PATH . 'public' . DS . $User['cover']) && @unlink(ROOT_PATH . 'public' . DS . $User['cover']);
                 }
 
                 $User = $this->UserModel->find($userid);
 
                 $data = [
                     'id'=>$User['id'],
                     'openid'=>$User['openid'],
                     'email'=>$User['email'],
                     'nickname'=>$User['nickname'],
                     'avatar'=>$User['avatar_cdn'],
                     'sex'=>$User['sex'],
                     'sex_text'=>$User['sex_text'],
                     'province'=>$User['province'],
                     'city'=>$User['city'],
                     'district'=>$User['district'],
                     'createtime'=>$User['createtime'],
                     'content'=>$User['content'],
                     'point'=>$User['point'],
                     'vip'=>$User['vip'],
                     'auth'=>$User['auth'],
                     'cover'=>$User['cover_cdn'],
                     'region'=>explode('-', $User['region']),
                     'region_text'=>$User['region']
                 ];
 
                 $this->success('更新个人资料成功',null,$data);
                 exit;
             }
         }
     }

    // 登录凭证校验
    public function code2Session($code)
    {
        $AppId = 'wxccc83c3f36033dec';
        $secret = 'd9ecf9e2a5e6ec74f93485cdd9173e9e';
        

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$AppId&secret=$secret&js_code=$code&grant_type=authorization_code";

        // 发送请求
        $result = $this->https_request($ApiUrl);

        $result = json_decode($result,true);

        if($result)
        {
            return $result;
        }else{
            return false;
        }

    }

     //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    protected function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
}
